package com.dailyblue.project.estate.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.project.estate.commons.bean.Community;
import com.dailyblue.project.estate.commons.handler.CommunityException;
import com.dailyblue.project.estate.commons.mapper.CommunityMapper;
import com.dailyblue.project.estate.commons.util.JsonResult;
import com.dailyblue.project.estate.commons.util.ResultTool;
import com.dailyblue.project.estate.service.CommunityService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther:Liu
 * @Testname:CommunityServiceImpl
 * @Date:2025/9/18 14:32
 */
@Service
public class CommunityServiceImpl extends ServiceImpl<CommunityMapper, Community> implements CommunityService {
    @Resource
    private CommunityMapper communityMapper;

    @Override
    public JsonResult saveCommunity(Community community) {
        boolean b = save(community);
        if (!b) {
            throw new CommunityException("添加失败");
        }
        return ResultTool.success("save success");
    }

    @Override
    public JsonResult findOneCommunity(String id) {
        Community community = getById(id);
        return ResultTool.success(community);
    }

    @Cacheable(cacheNames = "Communitys")
    public JsonResult findAllCommunity() {
        List<Community> list = list();
        return ResultTool.success(list);
    }

    @CacheEvict(cacheNames = "Communitys", allEntries = true)
    public JsonResult deleteCommunity(String id) {
        boolean b = removeById(id);
        if (!b) {
            throw new CommunityException("删除失败");
        }
        return ResultTool.success("delete success");
    }

    @CacheEvict(cacheNames = "Communitys", allEntries = true)
    public JsonResult updateCommunity(Community community) {
        UpdateWrapper<Community> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", community.getId());
        wrapper.set("name", community.getName());
        wrapper.set("address", community.getAddress());
        wrapper.set("code", community.getCode());
        wrapper.set("area", community.getArea());
        wrapper.set("total_buildings", community.getTotalBuildings());
        wrapper.set("total_households", community.getTotalHouseholds());
        wrapper.set("greening_rate", community.getGreeningRate());
        wrapper.set("thumbnail", community.getThumbnail());
        wrapper.set("status", community.getStatus());
        int i = communityMapper.update(wrapper);
        if (i != 1) {
            throw new CommunityException("更新失败");
        }
        return ResultTool.success("update success");
    }
}
